package com.luck.easyfoodbatch.custom;

import android.content.Context;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.os.Environment;
import android.os.Looper;
import android.os.RemoteException;
import android.os.StatFs;

import com.luck.easyfoodbatch.entity.AppInfo;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by xiaoqi on 2016/8/30.
 */
public class Utility {
    public static long appSize = 0;

    public static int dip2px(Context context, float px) {
        final float scale = getScreenDensity(context);
        return (int) (px * scale + 0.5);
    }

    private static float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    /**
     * 获取手机内部剩余存储空间
     *
     * @return
     */
    public static long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 获取手机内部总的存储空间
     *
     * @return
     */
    public static long getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    /**
     * 获得App应用的大小
     *
     * @param context
     * @param pkgName
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static void getPkgSize(final Context context, String pkgName, final AppInfo appInfo) throws NoSuchMethodException,
            InvocationTargetException, IllegalAccessException {
        // getPackageSizeInfo是PackageManager中的一个private方法，所以需要通过反射的机制来调用
        Method method = PackageManager.class.getMethod("getPackageSizeInfo",
                String.class, IPackageStatsObserver.class);
        // 调用 getPackageSizeInfo 方法，需要两个参数：1、需要检测的应用包名；2、回调
        method.invoke(context.getPackageManager(), pkgName,
                new IPackageStatsObserver.Stub() {
                    @Override
                    public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
                        // 子线程中默认无法处理消息循环，自然也就不能显示Toast，所以需要手动Looper一下
                        Looper.prepare();
                        // 从pStats中提取各个所需数据
//						Toast.makeText(context, "缓存大小=" + Formatter.formatFileSize(context, pStats.cacheSize) +
//										"\n数据大小=" + Formatter.formatFileSize(context, pStats.dataSize) +
//										"\n程序大小=" + Formatter.formatFileSize(context, pStats.codeSize),
//								Toast.LENGTH_LONG).show();
                        appInfo.setAppCatchSize(pStats.cacheSize);
                        appInfo.setAppDataSize(pStats.dataSize);
                        appInfo.setAppCodeSize(pStats.codeSize);
                        appInfo.setAppSize(pStats.codeSize + pStats.dataSize + pStats.cacheSize);
                        // 遍历一次消息队列，弹出Toast
                        Looper.loop();
                    }
                });
    }

    /**
     * 获得文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }
}
